Getting User Data in Flask — Part 2

In this next series, let's begin implementing the Create To-Do Item functionality in our To-Do app. We'll preview conceptually how we'd use a form to send a POST request to our server to begin a request for to-do item creation, and then implement it in code.

Video Correction Notes

  • Response Body should be changed to Request Body, throughout.

Let's start coding!

These next videos walk through how to implement a form that successfully creates new todo items in our backend database.

Challenge yourself

Can you implement the MVC layers of this create functionality without watching the walk-throughs? Try it out in the interactive workspace at the end of this page!

Developing our view and running the app in debug mode

Code

index.html
<html>
  <head>
    <title>Todo App</title>
  </head>
  <body>
    <form method="post" action="/todos/create">
      <input type="text" name="description" />
      <input type="submit" value="Create" />
    </form>
    <ul>
      {% for d in data %}
      <li>{{ d.description }}</li>
      {% endfor %}
    </ul>
  </body>
</html>

Try it now in the interactive workspace below.

Developing the controller

Horray!

We have a fully working MVC flow capable of creating new todo items from the view, interacting with models to create those new records, and then updating our view to show them!

Code

app.py
@app.route('/todos/create', method=['POST'])
def create_todo():
  description = request.form.get('description', '')
  todo = Todo(description=description)
  db.session.add(todo)
  db.session.commit()
  return redirect(url_for('index'))
terminal commands
$ FLASK_APP=app.py FLASK_DEBUG=true flask run
$ psql todoapp
>>> select * from todos;

Let's review how we implemented the flow of data in our app!

Follow along!

In the interactive workspace below, practice implementing the ability to Create To-Do items.

  • The view (HTML form)
  • The controller (that receives the form submission)
  • The model interactions (within the controller)

Starter Code

The workspace below is based on prior work you may have done in previous practices. The starter code below is meant to help you start on a clean starting point if needed.

app.py
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://udacitystudios@localhost:5432/todoapp'
db = SQLAlchemy(app)

class Todo(db.Model):
  __tablename__ = 'todos'
  id = db.Column(db.Integer, primary_key=True)
  description = db.Column(db.String(), nullable=False)

  def __repr__(self):
    return f'<Todo {self.id} {self.description}>'

db.create_all()

@app.route('/')
def index():
  return render_template('index.html', data=Todo.query.all())
templates/index.html
<html>
  <head>
    <title>Todo App</title>
  </head>
  <body>
    <ul>
      {% for d in data %}
      <li>{{ d.description }}</li>
      {% endfor %}
    </ul>
  </body>
</html>
Menu
full screen

Expand